using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Management;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace BizTalk.BuildGenerator.Tasks
{
    /// <summary>
    /// Task to create a send handler
    /// </summary>
    public class CreateSendHandler : Task
    {
        private string _AdapterName;
        private string _HostName;        

        /// <summary>
        /// Host name
        /// </summary>
        [Required]
        public string HostName
        {
            get { return _HostName; }
            set { _HostName = value; }
        }
        /// <summary>
        /// Adapter name
        /// </summary>
        [Required]
        public string AdapterName
        {
            get { return _AdapterName; }
            set { _AdapterName = value; }
        }

        /// <summary>
        /// The execute method
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.CreateOnly;

                ManagementClass handlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_SendHandler2", null);

                foreach (ManagementObject handler in handlerManagementClass.GetInstances())
                {
                    if ((string)handler["AdapterName"] == this._AdapterName
                        && (string)handler["HostName"] == this._HostName)
                    {
                        handler.Delete();
                    }
                }

                ManagementObject handlerInstance = handlerManagementClass.CreateInstance();
                handlerInstance["AdapterName"] = this._AdapterName;
                handlerInstance["HostName"] = this._HostName;
                handlerInstance.Put(options);

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(this.GetType().FullName, ex.ToString());
                throw;
            }
        }
    }
}
